package com.kujie.controller;

import com.kujie.enums.PromptRoleEnum;
import com.kujie.utils.SmartPromptUtil;
import com.kujie.utils.TextUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@Slf4j
@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*")
public class ChatController {

    @Resource(name = "buildChatClient")
    private ChatClient chatClient;

    @Resource(name = "buildCurrentChatClient")
    private ChatClient currentChatClient;

    @GetMapping(value = "/steamChat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> steamChat(@RequestParam("input") String input) {
        String role = "";
        String prompt = "";
        String currentPrompt = "";

        // 获取默认提示词
        prompt = SmartPromptUtil.generateSystemPrompt(PromptRoleEnum.getRoleName(role));

        // ai初步判断是什么类型的操作
        ChatClient.CallResponseSpec call = chatClient.prompt().system(prompt).user(input).call();
        String content = call.content();

        // 获取角色
        role = TextUtil.getLastCommand(content);

        try {
            // 获取指定提示词
            currentPrompt = SmartPromptUtil.generateSystemPrompt(PromptRoleEnum.getRoleName(role));
            return currentChatClient.prompt().system(currentPrompt).user(input)
                    .stream()
                    .content();
        } catch (Exception e) {
            log.error("处理请求时发生错误", e);
            return Flux.just("抱歉，处理您的请求时出现错误，请稍后重试。");
        }
    }
}
